using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExcelTemplateEngine.Exceptions
{
    /// <summary>
    /// 模板引擎基础异常类
    /// </summary>
    public abstract class TemplateEngineException : Exception
    {
        /// <summary>
        /// 错误代码
        /// </summary>
        public string ErrorCode { get; }
        
        /// <summary>
        /// 错误上下文信息
        /// </summary>
        public Dictionary<string, object> Context { get; }
        
        protected TemplateEngineException(string errorCode, string message) 
            : base(message)
        {
            ErrorCode = errorCode;
            Context = new Dictionary<string, object>();
        }
        
        protected TemplateEngineException(string errorCode, string message, Exception? innerException) 
            : base(message, innerException)
        {
            ErrorCode = errorCode;
            Context = new Dictionary<string, object>();
        }
        
        /// <summary>
        /// 添加上下文信息
        /// </summary>
        public virtual void AddContext(string key, object value)
        {
            Context[key] = value;
        }
        
        /// <summary>
        /// 获取详细的错误信息
        /// </summary>
        public virtual string GetDetailedMessage()
        {
            var sb = new StringBuilder();
            sb.AppendLine($"Error Code: {ErrorCode}");
            sb.AppendLine($"Message: {Message}");
            
            if (Context.Any())
            {
                sb.AppendLine("Context:");
                foreach (var kvp in Context)
                {
                    sb.AppendLine($"  {kvp.Key}: {kvp.Value}");
                }
            }
            
            if (InnerException != null)
            {
                sb.AppendLine($"Inner Exception: {InnerException.Message}");
            }
            
            return sb.ToString();
        }
    }
}